package com.central.apps.handler.contract;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.service.HandlerService;
import com.central.apps.entity.CostAttribute;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.apps.handler.purchase.PurchasePaymentApplyHandler;
import com.central.apps.service.CostAccumulationService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2022/9/27.
 */
@Slf4j
@Component
public class ConcollandpayHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FileSynUtilService fileSynUtilService;
    @Autowired
    private CostAccumulationService costAccumulationService;
    @Autowired
    private PurchasePaymentApplyHandler purchasePaymentApplyHandler;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        //System.out.println("=============================collandpay============" + flowNode.getId());
        if (flowNode.getId().equals("submit")) {
            //审核通过后增加库存
            boolean flag = op.isFlag();//判断是否审核通过
            if (flag) {
                //判断是否有明细数据
                List<Map<String, Object>> list2 = handlerService.findBySql("select * from gq_concolldetailed where receivingdetailid=" + id);
                if (CollectionUtils.isEmpty(list2)) {
                    return "请添加付款明细行数据再提交申请";
                }
                //查询接收入库主表gq_concollandpay
                List<Map<String, Object>> list = handlerService.findBySql("select * from gq_concollandpay where id=" + id);
                if (CollectionUtils.isNotEmpty(list)) {
                    String concode = (String) list.get(0).get("concode");
                    String nodecode = (String) list.get(0).get("contractnodenum");
                    String sqlrecord = "select concode as concode, receivingdetailid, contractnodenum, sum(shouldpaying) as shouldpaying,sum(receivingamount) as receivingamount" +
                            "  from gq_concolldetailed group by concode,contractnodenum,receivingdetailid HAVING concode = '" + concode + "' and contractnodenum='" + nodecode + "' and receivingdetailid in (select id from gq_concollandpay )";
                    List<Map<String, Object>> listrecord = handlerService.findBySql(sqlrecord);
                    if (CollectionUtils.isNotEmpty(listrecord)) {
                        String receivingamount = MapUtils.getString(listrecord.get(0), "receivingamount");//此次累计收付款金额
                        if (ToolUtil.isEmpty(receivingamount)) {
                            receivingamount = "0";
                        }
                        String receivingamounttax = MapUtils.getString(list.get(0), "receivingamounttax");//节点收付款金额
                        if (ToolUtil.isEmpty(receivingamounttax)) {
                            receivingamounttax = "0";
                        }
                        String sumamounttax = MapUtils.getString(list.get(0), "sumamounttax");//节点累计收付款金额
                        if (ToolUtil.isEmpty(sumamounttax)) {
                            sumamounttax = "0";
                        }
                        BigDecimal sumamounttaxs = new BigDecimal(sumamounttax);//
                        BigDecimal receivingamounts = new BigDecimal(receivingamount);
                        BigDecimal receivingamounttaxs = new BigDecimal(receivingamounttax);
                        // System.out.println(pricetaxtotal.add(pricetaxtotals));
//                        float receivingamount =(float) listrecord.get(0).get("receivingamount");//明细汇总
//                        float receivingamounttax = (float) list.get(0).get("receivingamounttax");//节点收付款
                        if (receivingamounttaxs.compareTo(receivingamounts.add(sumamounttaxs)) < 0) {
                            //return "收付款明细汇总跟节点收付款不相等，请修改明细在提交";
                            return "节点累计收付款金额不能大于节点收付款金额";
                        }
                    }
                }

            }
        }



        return null;
    }
    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if (flowNode.getId().equals("appval") && op.isFlag()) {
            purchasePaymentApplyHandler.setConNodeInfo(app, id, flowNode, op, "gq_concollandpay","合同收款");
            // 调用成本归集
            try {
                costAccumulation(op.getVariables());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 成本归集
     *
     * @param map
     */
    private void costAccumulation(Map<String, Object> map) throws Exception {
        CostAttribute costAttribute = new CostAttribute();
        costAttribute.setName(MapUtils.getString(map, "conname"));// 业务申请名称
        costAttribute.setProId(MapUtils.getInteger(map, "proid"));// 项目id
        costAttribute.setSubjectNo(MapUtils.getString(map, "subjectno"));// 课题号
        costAttribute.setTaskid(MapUtils.getInteger(map, "taskid"));// 任务id
        Double receivingamounttax = MapUtils.getDouble(map, "receivingamounttax");
        costAttribute.setTotalCost(BigDecimal.valueOf(receivingamounttax));// 总计金额
        costAttribute.setCostItemId(MapUtils.getInteger(map, "pbid"));// 预算项id
        costAttribute.setOrderId(MapUtils.getInteger(map, "id").toString());// 关联合同/出入库等单据id
        costAttribute.setOrderNo(MapUtils.getString(map, "concode"));// 关联合同/出入库等单据编号
        costAttribute.setCostSource("合同付款");

        costAccumulationService.costAccumulation(costAttribute);
    }
}
